﻿using System.Diagnostics;
using System.Text;
using Growatt.Component.Cls;
using Growatt.ShinebusService.Model;
using Newtonsoft.Json;
using static Growatt.ShinebusServiceUploadPack.Service.FeishuHelper.FileUploadUtils;

namespace Growatt.ShinebusServiceUploadPack.Service.FeishuHelper
{
    public class OfficialRecFeishu : BaseHttpClient
    {
        private readonly ILogger<OfficialRecFeishu> logger;

        public OfficialRecFeishu(IHttpClientFactory httpClientFactory, ILogger<OfficialRecFeishu> logger, string urlUploadFileFieshuUrl)
            : base(httpClientFactory, urlUploadFileFieshuUrl)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 获取登录时间
        /// </summary>
        /// <param name="recordBody"></param>
        public async Task<FirmwareUploadInfoResponse> InsertServerAsync(RecordFieldsFileUploadUtilsBody recordBody, string searchKey, string fileToken, string urlUploadFileFieshuUrl)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            searchKey = System.IO.Path.GetFileName(searchKey);
            var Body = string.Empty;
            var listVersionRecord = await SearchServerAsync(urlUploadFileFieshuUrl);
            if (listVersionRecord == null)
                return new FirmwareUploadInfoResponse() { UploadStatus = -1, Message = "无法获取指定版本" };
            var list = listVersionRecord.Where(o => o.fields.升级后目标版本 != null).ToList().Select(o => o.fields.升级后目标版本.FirstOrDefault().text);
            if (!list.Contains(searchKey)) //新增
            {
                return new FirmwareUploadInfoResponse() { UploadStatus = 0, Message = $"无法获取指定版本:{searchKey}" };
                #region 判断是否新增
                //FileUploadUtils fileUploadUtils = new FileUploadUtils(baseID, tablesID, this.accessToken);//更新表格ID
                //var to = recordBody.fields.升级前运行版本.FirstOrDefault();//获取附件的token
                //if (to != null)
                //{
                //    await fileUploadUtils.InsertServerOnlyOneFileAsync(to.file_token, recordBody.fields);
                //    return new FirmwareUploadInfoResponse() { UploadStatus = 1, Message = "新增:上传飞书文档成功" };
                //}
                //await fileUploadUtils.upload_OnlyOneFileAsynchronous(FilePath, DuiHelpers.DuiHelperJson.ObjectToJson(recordBody));
                #endregion
            }
            else //更新
            {
                var itemData = listVersionRecord.Where(o => o.fields.升级后目标版本 != null).ToList().FirstOrDefault(o => o.fields.升级后目标版本.FirstOrDefault().text.Equals(searchKey));
                if (itemData != null)
                {
                    if (itemData.fields.设备型号 != null)
                    {
                        recordBody.fields.设备型号 = itemData.fields.设备型号;
                    }
                    var code = await UpdateServerAsync(recordBody, itemData.record_id, urlUploadFileFieshuUrl);
                    if (code == -1)
                    {
                        Debug.WriteLine("更新失败");
                    }
                    else
                    {
                        return new FirmwareUploadInfoResponse() { UploadStatus = 1, Message = "更新:上传飞书文档成功" };
                    }
                }
            }
            return new FirmwareUploadInfoResponse() { UploadStatus = 0, Message = "无法获取指定版本" };
        }

        public async Task<List<UplaodInfoItem>> SearchServerAsync(string urlUploadFileFieshuUrl)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();

            // 定义请求地址
            string url = $"{BaseAddress}bitable/v1/apps/{baseID}/tables/{tablesID}/records/search?page_size=499";

            // 创建请求体
            var requestBody = new { view_id = ViewId };
            string jsonBody = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            // 发送 POST 请求
            string responseContent = await SendPostRequestAsync(url, content, logger, accessToken);
            if (!string.IsNullOrEmpty(responseContent))
            {
                // 解析响应内容
                var jsonData = JsonConvert.DeserializeObject<UplaodInfoRootobject>(responseContent);

                // 返回结果
                return jsonData.data.items.ToList();
            }
            return null;
        }

        public async Task<int> UpdateServerAsync(RecordFieldsFileUploadUtilsBody recordBody, string recordid, string urlUploadFileFieshuUrl)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            var jsonBody = JsonConvert.SerializeObject(recordBody);

            using (HttpClient client = _httpClientFactory.CreateClient("OSS"))
            {
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Put,
                    RequestUri = new Uri($"https://open.feishu.cn/open-apis/bitable/v1/apps/{baseID}/tables/{tablesID}/records/{recordid}"),
                    Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"),
                };
                request.Headers.Add("Authorization", $"Bearer {accessToken}");

                var response = await client.SendAsync(request);
                var responseContent = await response.Content.ReadAsStringAsync();

                // 反序列化为对象
                var updateResponse = JsonConvert.DeserializeObject<UpdateResponse>(responseContent);
                if (updateResponse != null)
                {
                    return updateResponse.Code;
                }
            }

            return -1;
        }
    }
}
